<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Notifications\Notifiable;

class Book extends Model
{
    protected $fillable=['bid','cid','name','author','publisher','total_num','remain_num','price','introduction'];
    protected $table = 'books';
    public $timestamps = true;
    protected $primaryKey = 'bid';

    public static function addBooks($request,$cid){
        $name = $request->input('name');
        $author = $request->input('author');
        $publisher = $request->input('publisher');
        $total_num = $request->input('total_num');
        $price = $request->input('price');

        $result = self::create([
           'name' => $name,
           'author' => $author,
           'publisher' => $publisher,
            'total_num' => $total_num,
            'price' => $price,
            'remain_num' => $total_num,
            'cid' => $cid,
            'introduction' => '',
        ]);

        return $result;
     }

     public static function getList(){
        $result = self::where('total_num','>',0)->get()->toArray();
        return $result;
    }

    public static function deleteBooks($request){
        $bid = $request->input('bid');
        $number = $request->input('number');
        $total_num = self::where('bid',$bid)->select('total_num')->first()->toArray();
        $remain_num = self::where('bid',$bid)->select('remain_num')->first()->toArray();
        $total_num = $total_num['total_num'];
        $remain_num = $remain_num['remain_num'];
        if ($number>$remain_num){
            return false;
        }else{
            $total_num -= $number;
            $remain_num -= $number;
            $result = self::where('bid',$bid)->update([
               'total_num' => $total_num,
               'remain_num' =>$remain_num,
            ]);
            return $result;
        }
    }

    public static function increaseBooks($request){
        $bid = $request->input('bid');
        $number = $request->input('number');
        $total_num = self::where('bid',$bid)->select('total_num')->first()->toArray();
        $remain_num = self::where('bid',$bid)->select('remain_num')->first()->toArray();
        $total_num = $total_num['total_num'] + $number;
        $remain_num = $remain_num['remain_num'] + $number;
        $result = self::where('bid',$bid)->update([
            'total_num' => $total_num,
            'remain_num' => $remain_num,
        ]);
        return $result;
    }

    public static function categoryDetail($cid){
        $books = self::where('cid',$cid)->where('total_num','>',0)->get()->toArray();
        return $books;
    }

}